<template>
  <page-container title="快捷登录" :showBack="true">
    <template v-slot:nav-left>
      <view class="nav-left" @click="goBack">
        <uni-icons type="left" size="20" color="#d4af37"></uni-icons>
      </view>
    </template>
    <view class="quick-login-container">
      <view class="title-section">
        <image src="/static/logo.png" mode="aspectFit" class="logo-icon"></image>
        <text class="main-title">金盈晟珠宝</text>
        <!-- <text class="sub-title">授权手机号快速登录/注册</text> -->
      </view>

      <view class="action-section">
        <!-- :disabled="loading || !isAgreed" -->
        <!--  -->
        <button class="wx-phone-btn" type="primary" :open-type="isAgreed ? 'getPhoneNumber' : ''" @click="onClickWxPhone" @getphonenumber="onGetPhoneNumber">
          {{ loading ? '登录中...' : '微信一键登录' }}
        </button>
	

        <view class="agreement" @click="toggleAgreement">
          <view class="checkbox" :class="{ checked: isAgreed }">
            <uni-icons v-if="isAgreed" type="checkmark" size="16" color="#fff"></uni-icons>
          </view>
          <text class="agreement-text">我已知晓</text>
          <text class="agreement-link" @click.stop="openPrivacyPolicy">《隐私政策》</text>
          <text class="agreement-text">和</text>
          <text class="agreement-link" @click.stop="openServiceAgreement">《注册和服务协议》</text>
        </view>

        <view class="other-actions">
          <text class="other-text" @click="goAccountLogin">使用账号密码/验证码登录</text>
        </view>
      </view>
    </view>
  </page-container>

</template>

<script>
import uniIcons from '@dcloudio/uni-ui/lib/uni-icons/uni-icons.vue'

export default {
  name: 'QuickLoginPage',
  components: { uniIcons },
  data() {
    return {
      loading: false,
      isAgreed: false
    }
  },
  methods: {
    goBack() {
		const pages = getCurrentPages();
		if (pages.length > 1) {
		  uni.navigateBack({
		    delta: pages.length - 1 // 返回的层数，这里是除了当前页外的所有页面
		  });
		} else {
		  // 处理已经是第一层的情况，例如重定向到首页等
		  setTimeout(()=>{
			  uni.switchTab({
			    url: '/pages/home/index' // 返回到首页
			  });
		  },200);
		}
        
    },
    toggleAgreement() {
      this.isAgreed = !this.isAgreed
    },
    openPrivacyPolicy() {
      uni.navigateTo({ url: '/pages/login/privacyPolicy' })
    },
    openServiceAgreement() {
      uni.navigateTo({ url: '/pages/login/agreement' })
    },
    goAccountLogin() {
      uni.redirectTo({ url: '/pages/login/index' })
    },
    onClickWxPhone() {
      if (this.loading) return
      if (!this.isAgreed) {
        uni.showToast({ title: '请先同意协议', icon: 'none' })
      }
    },
    async ensureOpenId() {
      const hasOpenId = uni.getStorageSync('openId')
      if (hasOpenId) return hasOpenId
      // 小程序环境通过 wx.login 获取 code 由后端换取 openId
      try {
        const loginRes = await new Promise((resolve, reject) => {
          uni.login({ provider: 'weixin', success: resolve, fail: reject })
        })
        const code = loginRes.code
        if (!code) return ''
        const res = await this.$http.get(`/applet/customer/wxAppletGetOpenId/${code}`)
        if (res.data) {
          uni.setStorageSync('openId', res.data)
        }
        // if (res.data && res.data.loginInfo) {
        //   uni.setStorageSync('token', res.data.loginInfo.token)
        //   uni.setStorageSync('customerInfo', res.data.loginInfo)
        // }
        return uni.getStorageSync('openId') || ''
      } catch (e) {
        return ''
      }
    },
    async onGetPhoneNumber(e) {
      console.log(123, 'onGetPhoneNumber', this.loading, this.isAgreed);
      if (this.loading) return
      if (!this.isAgreed) {
        uni.showToast({ title: '请先同意协议', icon: 'none' })
        return;
      }
      const { detail } = e
      console.log(detail, 'detail');

      if (!detail || detail.errMsg !== 'getPhoneNumber:ok') {
        uni.showToast({ title: '未授权手机号,请使用其他方式登录', icon: 'none' })
        return
      }

      const { code } = detail

      this.loading = true
      try {
        const openId = await this.ensureOpenId()
        const payload = {
          code: code || '',
          openId: openId || ''
        }
        const result = await this.$http.post('/applet/customer/wxAppletLogin', payload)
        console.log(result.data, 'result.data');
        if (result.data && result.data.openId) {
          uni.setStorageSync('openId', result.data.openId)
        }
		const isLogin = result.data.isLogin;
		const isRegister = result.data.isRegister;
		//如果客户授权手机号之后查询到没有注册，则跳转注册页面，，如果已注册但是没有审核完成，则提示审核消息
		console.log(isRegister,"|",isLogin);
		if(result.data && !isLogin ){
			if(!isRegister){
				uni.navigateTo({
				  url: '/pages/login/registered?phone='+result.data.phone
				});
				return;
			}else{
				uni.showModal({
				  title: '提示',
				  content: '注册用户待审核，请联系平台审核',
				  showCancel: false,
				  success: (res) => {
				    if (res.confirm) {
				      return
				    }
				  }
				})
				return;
			}
		}
        if (result.data && result.data.loginInfo) {
          uni.setStorageSync('customerInfo', result.data.loginInfo)
          uni.setStorageSync('token', result.data.loginInfo.token)
        }
        uni.showToast({ title: '登录成功', icon: 'success' })
        setTimeout(() => {
          uni.switchTab({ url: '/pages/home/index' })
        }, 300)
      } catch (err) {
        uni.showToast({ title: err.msg || '登录失败，请稍后重试', icon: 'none' })
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/uni.scss';

.quick-login-container {
  min-height: 100vh;
  background-color: #ffffff;
}

.title-section {
  padding: 60rpx 0 40rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo-icon {
  width: 200rpx;
  height: 200rpx;
}

.main-title {
  margin-top: 16rpx;
  font-size: 40rpx;
  font-weight: 600;
  color: #0B1F20;
}

.sub-title {
  margin-top: 8rpx;
  font-size: 26rpx;
  color: #666666;
}

.action-section {
  padding: 0 30rpx;
  margin-top: 60rpx;
}

.wx-phone-btn {
  background: $uni-text-color-orange;
  border-radius: 16rpx;
  padding: 12rpx;
  text-align: center;
}

.agreement {
  margin-top: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #d4af37;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox.checked {
  background-color: #d4af37;
}

.agreement-text {
  font-size: 24rpx;
  color: #999999;
}

.agreement-link {
  font-size: 24rpx;
  color: $uni-text-color-orange;
}

.other-actions {
  margin-top: 30rpx;
  text-align: center;
}

.other-text {
  font-size: 26rpx;
  color: #666666;
}

/* 备用勾选图标样式 */
.checkbox.checked::after {
  content: '';
  width: 18rpx;
  height: 10rpx;
  border: 2rpx solid #ffffff;
  border-top: none;
  border-right: none;
  transform: rotate(-45deg);
  margin-top: -6rpx;
}
</style>
